import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

const request = axios.create({ baseURL: 'http://localhost:8888/api/private/v1', timeout: 500000 })

request.interceptors.request.use(config => {
  nprogress.start()
  const { token } = store.state.userInfo
  if (token) { config.headers.Authorization = token }
  return config
})

request.interceptors.response.use(({ data }) => {
  if (!data?.meta?.status) {
    nprogress.done()
    return Promise.reject(new Error('请求失败'))
  }
  if (data.meta.status === 200 || data.meta.status === 201) {
    nprogress.done()
    return data.data
  } else {
    if (data.meta.status === 400 && data.meta.msg === '无效token') {
      store.commit('logOut')
      Message.warning('登录过期,请重新登录') // token 过期
      nprogress.done()
      return Promise.reject(new Error(data.meta.msg))
    }
    Message.warning(data.meta.msg) // 业务错误
    nprogress.done()
    return Promise.reject(new Error(data.meta.msg))
  }
}, (err) => {
  Message.warning(err.message) // 接口没调通
  nprogress.done()
  return Promise.reject(err)
})

export default request
